const path = require('path')
const fs = require('fs')

// 检查目录是否存在，不存在则创建
const checkDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }
}

// 获取命令行参数
const args = process.argv.slice(2)
const mode = args[0] || 'production'

// 读取环境变量
require('dotenv').config({ path: path.resolve(__dirname, `.env.${mode}`) })

// 静态资源目录
const DIST_PATH = path.resolve(__dirname, './dist')
checkDir(DIST_PATH)

// 创建Nginx配置
const createNginxConfig = () => {
  const nginxConfig = `
server {
    listen 80;
    server_name example.com;  # 替换为实际域名
    
    # 开启gzip
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 9;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
    
    # 静态资源目录
    root /var/www/html;
    
    location / {
        # 尝试查找文件，不存在则回退到index.html
        try_files $uri $uri/ /index.html;
        index index.html;
    }
    
    # API代理
    location /api/ {
        proxy_pass http://api-server:3000/;  # 替换为实际API服务器地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # 缓存静态资源
    location ~* \\.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1d;
    }
    
    # 安全相关头信息
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
}
`
  fs.writeFileSync(path.resolve(__dirname, 'nginx.conf'), nginxConfig)
  console.log('Nginx配置文件已生成: nginx.conf')
}

// 创建PM2配置
const createPM2Config = () => {
  const pm2Config = {
    apps: [
      {
        name: 'vue2-project',
        script: 'server.js',
        instances: 'max',
        exec_mode: 'cluster',
        env: {
          NODE_ENV: 'production',
          PORT: 8080
        },
        env_development: {
          NODE_ENV: 'development',
          PORT: 3000
        },
        env_test: {
          NODE_ENV: 'test',
          PORT: 8000
        }
      }
    ]
  }

  fs.writeFileSync(
    path.resolve(__dirname, 'ecosystem.config.js'),
    `module.exports = ${JSON.stringify(pm2Config, null, 2)}`
  )
  console.log('PM2配置文件已生成: ecosystem.config.js')
}

// 创建Docker配置
const createDockerConfig = () => {
  const dockerfile = `
FROM node:14-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install --production

COPY . .

EXPOSE 8080

CMD ["node", "server.js"]
`

  const dockerCompose = `
version: '3'

services:
  web:
    build: .
    ports:
      - "8080:8080"
    environment:
      - NODE_ENV=production
    volumes:
      - ./logs:/app/logs
    restart: always
`

  fs.writeFileSync(path.resolve(__dirname, 'Dockerfile'), dockerfile)
  fs.writeFileSync(path.resolve(__dirname, 'docker-compose.yml'), dockerCompose)
  console.log('Docker配置文件已生成: Dockerfile, docker-compose.yml')
}

// 根据命令行参数生成配置
console.log(`正在为 ${mode} 环境生成服务器配置文件...`)
createNginxConfig()
createPM2Config()
createDockerConfig()

console.log('所有服务器配置文件生成完毕!')
console.log('可以根据实际部署环境选择使用Express(server.js)、Nginx(nginx.conf)、PM2(ecosystem.config.js)或Docker进行部署')
